package com.zhang.common.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpResponseEncoder;

import java.util.ArrayList;
import java.util.List;

/**
 * 公共 响应 编码器
 * @author 98265
 */
public class MyHttpResponseEncoder extends HttpResponseEncoder {
    @Override
    public void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
        super.encode(ctx, msg, out);
    }

    /**
     * 重载编码方法
     * @param ctx
     * @param msg
     * @param channel
     * @throws Exception
     */
    public void encodeAndSend(ChannelHandlerContext ctx, Object msg, Channel channel) throws Exception{
        List<Object> out = new ArrayList<>();
        super.encode(ctx, msg, out);
        for(Object o:out){
            ByteBuf byteBuf = (ByteBuf) o;
            channel.writeAndFlush(Unpooled.wrappedBuffer(byteBuf)).addListener(ChannelFutureListener.CLOSE);
        }
    }
}
